<template>
  <div class="expert-users">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>专家用户管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索专家..."
              style="width: 200px"
              class="mr-3"
              clearable
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleAdd">添加专家</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredExperts" style="width: 100%" v-loading="loading">
        <el-table-column prop="expertId" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="title" label="职称" width="120" />
        <el-table-column prop="field" label="领域" width="150" />
        <el-table-column prop="consultationCount" label="咨询量" width="100" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="scope">
            {{ scope.row.rating?.toFixed(1) || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="certificationStatus" label="认证状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.certificationStatus)">
              {{ scope.row.certificationStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="row.avatar || '/images/default-avatar.jpg'" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除该专家吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑专家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加专家' : '编辑专家'"
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="expertFormRef"
        :model="expertForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item v-if="dialogType === 'add'" label="用户名" prop="username">
          <el-input v-model="expertForm.username" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="expertForm.password" type="password" show-password />
          <div class="form-tip">不填写则使用默认密码：123456</div>
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="手机号" prop="phone">
          <el-input v-model="expertForm.phone" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="expertForm.name" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="expertForm.title" />
        </el-form-item>
        <el-form-item label="专业领域" prop="field">
          <el-input v-model="expertForm.field" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input 
            v-model="expertForm.introduction" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="认证状态" prop="certificationStatus">
          <el-select v-model="expertForm.certificationStatus" style="width: 100%">
            <el-option :label="CERTIFICATION_STATUS.CERTIFIED" :value="CERTIFICATION_STATUS.CERTIFIED" />
            <el-option :label="CERTIFICATION_STATUS.PENDING" :value="CERTIFICATION_STATUS.PENDING" />
            <el-option :label="CERTIFICATION_STATUS.UNCERTIFIED" :value="CERTIFICATION_STATUS.UNCERTIFIED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getExpertList, formatExpertData, addExpert, updateExpert, deleteExpert } from '@/api/expert'
import { addUser, isUsernameExists } from '@/api/user'

// 状态变量
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const experts = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const expertForm = ref({})
const expertFormRef = ref(null)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入专家姓名', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入职称', trigger: 'blur' }
  ],
  field: [
    { required: true, message: '请输入专业领域', trigger: 'blur' }
  ],
  certificationStatus: [
    { required: true, message: '请选择认证状态', trigger: 'change' }
  ]
}

// 认证状态常量
const CERTIFICATION_STATUS = {
  CERTIFIED: '已认证',
  PENDING: '认证中',
  UNCERTIFIED: '未认证'
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '已认证': return 'success'
    case '认证中': return 'warning'
    case '未认证': return 'danger'
    default: return 'info'
  }
}

// 过滤专家列表
const filteredExperts = computed(() => {
  if (!searchQuery.value) return experts.value
  
  const query = searchQuery.value.toLowerCase()
  return experts.value.filter(expert => 
    expert.name?.toLowerCase().includes(query) ||
    expert.title?.toLowerCase().includes(query) ||
    expert.field?.toLowerCase().includes(query)
  )
})

// 获取专家列表
const fetchExperts = async () => {
  loading.value = true
  try {
    const response = await getExpertList()
    if (response.code === 200) {
      experts.value = response.data.map(formatExpertData)
      total.value = response.data.length
    } else {
      throw new Error(response.message || '获取专家列表失败')
    }
  } catch (error) {
    console.error('获取专家列表失败:', error)
    ElMessage.error('获取专家列表失败')
  } finally {
    loading.value = false
  }
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  expertForm.value = {
    username: '',
    password: '',
    phone: '',
    name: '',
    title: '',
    field: '',
    introduction: '',
    certificationStatus: CERTIFICATION_STATUS.UNCERTIFIED,
    consultationCount: 0,
    rating: 0
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  expertForm.value = {
    expertId: row.expertId,
    name: row.name,
    title: row.title,
    field: row.field,
    introduction: row.introduction,
    certificationStatus: row.certificationStatus,
    consultationCount: row.consultationCount || 0,
    rating: row.rating || 0,
    userId: row.userId
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该专家吗？此操作将同时删除专家信息和对应的用户账号，且不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    console.log('Deleting expert with ID:', row.expertId)
    const response = await deleteExpert(row.expertId)
    console.log('Delete response:', response)

    if (response.code === 200) {
      ElMessage.success('删除成功')
      experts.value = experts.value.filter(expert => expert.expertId !== row.expertId)
      total.value = experts.value.length
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除专家失败', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理表单提交
const handleSubmit = () => {
  expertFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 检查用户名是否已存在
          const checkResponse = await isUsernameExists(expertForm.value.username)
          if (checkResponse.code === 200 && checkResponse.data) {
            ElMessage.error('用户名已存在')
            return
          }

          // 先创建用户账号
          const userData = {
            username: expertForm.value.username,
            password: expertForm.value.password || '123456',
            phone: expertForm.value.phone,
            role: '专家',
            nickname: expertForm.value.name
          }
          
          console.log('Creating user with data:', userData)
          const userResponse = await addUser(userData)
          console.log('User creation response:', userResponse)
          
          if (userResponse.code !== 200) {
            throw new Error(userResponse.message || '创建用户账号失败')
          }

          // 创建专家信息
          const expertData = {
            userId: userResponse.data.userId,
            name: expertForm.value.name,
            title: expertForm.value.title,
            field: expertForm.value.field,
            introduction: expertForm.value.introduction,
            certificationStatus: expertForm.value.certificationStatus || '待认证'
          }
          
          console.log('Creating expert with data:', expertData)
          const expertResponse = await addExpert(expertData)
          console.log('Expert creation response:', expertResponse)
          
          if (expertResponse.code === 200) {
            ElMessage.success('添加专家成功')
            if (!expertForm.value.password) {
              ElMessage.info('默认密码为: 123456')
            }
            dialogVisible.value = false
            fetchExperts()
          } else {
            throw new Error(expertResponse.message || '添加专家失败')
          }
        } else {
          // 编辑模式
          const expertData = {
            expertId: expertForm.value.expertId,
            name: expertForm.value.name,
            title: expertForm.value.title,
            field: expertForm.value.field,
            introduction: expertForm.value.introduction,
            certificationStatus: expertForm.value.certificationStatus
          }
          
          const response = await updateExpert(expertData)
          if (response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchExperts()
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchExperts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchExperts()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchExperts()
}

onMounted(() => {
  fetchExperts()
})
</script>

<style scoped>
.expert-users {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.mr-3 {
  margin-right: 12px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style> 